//
//  CYAccountDetailViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/1.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYAccountDetailViewController.h"
#import "CYDataSourceDelegate.h"
#import "CYUserHeader.h"
#import "CYAccountCell.h"
#import "CYAccountTitleCell.h"
#import "CYAccountDetailModel.h"
@interface CYAccountDetailViewController (){
    NSUInteger _row; //显示多少条
    NSUInteger _page; //第几页
    NSUInteger status;//账户明细借口参数，3，为全部，2， 为支出，1，为收入
    
}
@property (nonatomic, strong) UITableView *tableView;//tableview
@property (nonatomic, strong) UITableView *little_tableview;//显示全部，收入，支出
@property (nonatomic, strong) CYButton *titleBtn;//navigationbar的title按钮
@property (nonatomic, strong) CYView *backview;//黑色透明背景
@property (nonatomic, strong) CYLabel *noRecordeLBL;//暂无记录
@property (nonatomic, strong) CYDelegate *delegate;
@property (nonatomic, strong) CYDataSource *datasource;
@property (nonatomic, strong) CYDelegate *little_delegate;
@property (nonatomic, strong) CYDataSource *little_datasource;
@property (nonatomic, copy) NSString *accountPlistName;//账户明细plist名称

@property (nonatomic, strong) CYAccountDetailModel *model;
@end

@implementation CYAccountDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _row = 10;
    _page = 1;
    status = 3;
    _accountPlistName = @"账户明细.plist";
    // Do any additional setup after loading the view.
}
/*懒加载*/
- (CYButton *)titleBtn{
    if (!_titleBtn) {
        _titleBtn = [[CYButton alloc]initWithTitle:@"账户明细" titleColor:[UIColor whiteColor] titleSize:AL(17) Image:@"xlsjx"];
        [_titleBtn setImage:[UIImage imageNamed:@"slsjx"] forState:UIControlStateSelected];
        [_titleBtn addTarget:self action:@selector(actionForTitleBtn:) forControlEvents:UIControlEventTouchUpInside];
        _titleBtn.imagePosition = RightPosition;
    }
    return _titleBtn;
}

- (CYView *)backview{
    if (!_backview) {
        _backview = [[CYView alloc]initWithColor:[UIColor lightGrayColor]];
        _backview.alpha = 0.5;
        [self.view addSubview:_backview];
        [self addTap];
        
        [_backview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0));
        }];
    }
    return _backview;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.mj_header = [CYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshDown)];//下拉刷新
        _tableView.mj_footer = [CYRefreshFooder footerWithRefreshingTarget:self refreshingAction:@selector(refreshUp)];//上拉加载
        [self.view addSubview:_tableView];
        [self setupTableview];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT, 0.0, 0.0, 0.0));
        }];
    }
    return _tableView;
}

- (UITableView *)little_tableview{
    if (!_little_tableview) {
        _little_tableview = [[UITableView alloc]init];
        _little_tableview.backgroundColor = [UIColor yellowColor];
        [self.view addSubview:_little_tableview];
        [self setupLittleTableview];
        
        
        [_little_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(-AL(PT(93*3)), 0.0, SCREEN_HEIGHT, 0));
        }];
    }
    return _little_tableview;
}

- (CYLabel *)noRecordeLBL{
    if (!_noRecordeLBL) {
        _noRecordeLBL = [[CYLabel alloc]initWithText:@"暂无纪录" size:AL(PT(30)) textcolor:TEXT_GRAY_COLOR];
        [self.view addSubview:_noRecordeLBL];
        
        [_noRecordeLBL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT + AL(PT(20)));
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(_noRecordeLBL.bounds.size);
        }];
    }
    return _noRecordeLBL;
}

/*设置tableview的代理*/
- (void)setupTableview{
    WS(self)
    _delegate = [[CYDelegate alloc]initWithCellHeight:AL(PT(115)) views:@[@{@"headerView":[CYUserHeader lightgrayView],@"headerHeight":@(AL(PT(20)))}] block:^(NSIndexPath *index) {
        
    }];
    
    _datasource  = [[CYDataSource alloc]initWithData:_model.recordModels identifier:@"CYAccountCell" block:^(id cell, id data) {
        [weakSelf bindCell:cell dict:data];
    }];
    
    _tableView.delegate = _delegate;
    _tableView.dataSource = _datasource;
    [_tableView setSeparatorInset:UIEdgeInsetsZero];
    [_tableView setLayoutMargins:UIEdgeInsetsZero];
}

/*设置littleTableview的代理*/
- (void)setupLittleTableview{
    WS(self)
    _little_delegate =  [[CYDelegate alloc]initWithCellHeight:AL(PT(94)) views:nil block:^(NSIndexPath *index) {
        [weakSelf selectedAccountTitleCell:index];
    }];
    
    _little_datasource  = [[CYDataSource alloc]initWithData:[self getTitleForAccountTitleCell:0] identifier:@"CYAccountTitleCell" block:^(id cell, id data) {
        [weakSelf bindAccountTitleCell:cell dict:data];
    }];
    
    _little_tableview.delegate = _little_delegate;
    _little_tableview.dataSource = _little_datasource;
}

/*绑定accountcell 数据*/
- (void)bindCell:(CYAccountCell *)cell dict:(CYRecordModel *)subModel{
    cell.title = (_type == AccountDetailType)?subModel.change_type:(_type == RechargeRecordType)?subModel.recharge_type:[NSString stringWithFormat:@"提款金额:%@",subModel.money];
    cell.money = (_type == AccountDetailType ||_type == RechargeRecordType)?subModel.money:subModel.state;
    cell.detailTitle = subModel.create_time;
    if (_type == RechargeRecordType)
        cell.state = subModel.state;
    
}

/*绑定accountTitleCell数据*/
- (void)bindAccountTitleCell:(CYAccountTitleCell *)cell dict:(NSDictionary *)dict{
    cell.title = dict[@"title"];
    cell.selectText = dict[@"select"];
}

/*选中accoutnTitleCell响应的方法*/
- (void)selectedAccountTitleCell:(NSIndexPath *)index{
    DeLog(@"账户明细页面，title按钮选中第%ld",(long)index.row);
    [self setupTitle:index];
    if (status != index.row) {
        status = (index.row == 0)?0:index.row;
        [self.model.recordModels removeAllObjects];
        _page = 1;
        [self https];
    }
}

/*设置vc的title*/
- (void)setupTitle:(NSIndexPath *)index{
    
    NSArray *array = [self getTitleForAccountTitleCell:(int)index.row];
    _little_datasource.dataArr = (NSMutableArray *)array;
    [_little_tableview reloadData];/*刷新选择的表格*/
    
    NSString *title = (index.row == 0)?@"账户明细":array[index.row][@"title"];
    [_titleBtn setTitle:title forState:UIControlStateNormal];
    [self performSelector:@selector(actionForTap)];
    
}

/*@pragma 构造littleTableview的显示内容*/
- (NSArray *)getTitleForAccountTitleCell:(int)index{
    
    NSMutableArray *select_values = [NSMutableArray arrayWithObjects:@"NO",@"NO",@"NO", nil];
    NSArray *title_values = @[@"全部",@"收入",@"支出"];
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0;  i < select_values.count; i ++) {
        select_values[i] = (index == i)?@"YES":@"NO";
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:select_values[i] forKey:@"select"];
        [dict setValue:title_values[i] forKey:@"title"];
        [array addObject:dict];
    }
    return (NSArray *)array;
}

- (void)setModel:(CYAccountDetailModel *)model{
    if (_model != model) {
        if (_model.current_page < 1 || !model)
            _model = model;
        else if(_model.current_page < model.total_page && _page > 1)
            [_model.recordModels addObjectsFromArray:model.recordModels];
        else if (_page == 1)
            [_model.recordModels replaceObjectsInRange:NSMakeRange(0, 10) withObjectsFromArray:model.recordModels];
        if (!_tableView){
            self.tableView.hidden =(_model.total_page > 0)?NO:YES;
            self.noRecordeLBL.hidden = (_model.total_page > 0)?YES:NO;
        }
        else{
            _datasource.dataArr = _model.recordModels;
            [_tableView reloadData];
        }
    }
}

/*添加背景的手势*/
- (void)addTap{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionForTap)];
    [_backview addGestureRecognizer:tap];
}

/*标题按钮响应方法*/
- (void)actionForTitleBtn:(CYButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected)
        [self showLittleTableView];
    else
        [self hiddenLittleTableView];
}

/*手势响应方法*/
- (void)actionForTap{
    _titleBtn.selected = NO;
    [self hiddenLittleTableView];
}

//
- (void)showLittleTableView{
    self.backview.hidden = self.little_tableview.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        _little_tableview.transform = CGAffineTransformMakeTranslation(0, AL(PT(93*3) + NAVIBAR_HEIGHT + STATUS_HEIGHT));
    }];
}

- (void)hiddenLittleTableView{
    [UIView animateWithDuration:0.3 animations:^{
        _little_tableview.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        _backview.hidden = YES;
    }];
}

//下拉刷新
- (void)refreshDown{
    _page = 1;
    [self https];
}

//上拉加载
- (void)refreshUp{
    _page = (int)_model.current_page;
    _page++;
    [self https];
}

//根据type获取接口
- (NSString *)getAPI{
    if (_type == AccountDetailType)//账户明细
        return API_account;
    else if (_type == RechargeRecordType)//充值记录
        return API_record;
    else if (_type == DrawRecordType)//提款记录
        return API_mention;
    return nil;
}

//构造请求体
- (NSDictionary *)getParameter{
    if (_type == AccountDetailType)//账户明细
        return @{@"username":[CYUser shareUser].username, @"token":[CYUser shareUser].token, @"page":@(_page), @"number":@(_row), @"status":@(status)};
    else if (_type == RechargeRecordType)//充值记录
        return @{@"username":[CYUser shareUser].username, @"token":[CYUser shareUser].token, @"page":@(_page),@"number":@(_row)};
    else if (_type == DrawRecordType)//提款记录
        return @{@"username":[CYUser shareUser].username, @"token":[CYUser shareUser].token, @"page":@(_page),@"number":@(_row)};
    return nil;
}

- (void)https{
    self.task = [CYHttps POST:[self getAPI] parameters:[self getParameter] showHUD:YES progress:nil success:^(id data) {
        if (_tableView){//如果tableview已经加载，结束下啦刷新动画
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
        DeLog(@"data %@" ,data);
        if ([data isKindOfClass:[NSDictionary class]])
            self.model = [CYAccountDetailModel mj_objectWithKeyValues:data];
    } failure:^(id string) {
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
    }];
    
}

- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:color];
    if (_type == AccountDetailType)
        self.navigationItem.titleView = self.titleBtn;
    else if (_type == RechargeRecordType || _type == DrawRecordType)
        self.navigationItem.title = (_type == RechargeRecordType)?@"充值记录":@"提款记录";
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self https];//网络请求
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

